package stack_queue;


import java.util.Stack;

/**
 * @program: play-structure
 * @description: 栈的应用：括号匹配
 * 遍历栈，先将左边的括号压入栈，然后再通过要进栈的元素跟栈顶元素是否匹配，匹配则弹出栈
 * @author: baichen
 **/
public class StackSample {
    public boolean isValid(String s) {
        //声明栈stack
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            //获取字符串的第i个元素
            char c = s.charAt(i);
            if (c == '(' || c == '[' || c == '{') {
                stack.push(c);
            } else {
                if (stack.isEmpty()) {
                    return false;
                }
                //取栈顶元素，与准备入栈的元素进行匹配
                char topChar = stack.pop();
                if (c == ')' && topChar != '(') {
                    return false;
                }
                if (c == ']' && topChar != '[') {
                    return false;
                }
                if (c == '}' && topChar != '{') {
                    return false;
                }
            }
        }
        return stack.isEmpty();     //判断栈是否为空,如果是空的话则匹配成功
    }

    public static void main(String[] args) {

        System.out.println((new StackSample()).isValid("()[]{}"));    //传入测试用例
        System.out.println((new StackSample()).isValid("([)]"));
    }
}

